package cn.fastoo.web.backstage.web.controller.system;

import cn.fastoo.common.dao.system.PermissionDao;
import cn.fastoo.common.dao.system.RoleDao;
import cn.fastoo.common.entity.system.Permission;
import cn.fastoo.common.entity.system.Role;
import cn.fastoo.common.sampleframe.search.Search;
import cn.fastoo.common.sampleframe.springside.Servlets;
import cn.fastoo.common.utils.ResponseTypeOutUtils;
import cn.fastoo.web.backstage.param.DataGridParam;
import cn.fastoo.web.backstage.utils.DataGridUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 角色页面 控制器.
 */
@Controller
@RequestMapping("/system/role")
public class RoleController {
	private static Logger logger = LoggerFactory.getLogger(RoleController.class);

	@Autowired
	private RoleDao roleDao;
	@Autowired
	private PermissionDao permissionDao;

	@RequiresPermissions(value = { "system:role:read" })
	@RequestMapping
	public String index(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		return "system/role";
	}

	/**
	 * 获取角色分页list数据，并转换为前端grid插件所需数据格式
	 * 
	 * @param dataGridParam
	 * @param request
	 * @param response
	 */
	@RequestMapping("/list")
	public void list(@ModelAttribute DataGridParam dataGridParam, HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
			Sort sort = new Sort(Direction.valueOf(dataGridParam.getOrder()), dataGridParam.getSort());
			PageRequest pageRequest = new PageRequest(dataGridParam.getPage(), dataGridParam.getRows(), sort);
			Page<Role> page = roleDao.findPage(new Search().addSearchFilter(searchParams).addPageRequest(pageRequest));
			ResponseTypeOutUtils.renderJson(response, DataGridUtils.PageToJson(page));
		} catch (Exception e) {
			e.printStackTrace();;
		}
	}

	/**
	 * 储存角色 新增和修改均使用同一方法
	 * 
	 * @param permission
	 * @param request
	 * @param response
	 */
	@RequiresPermissions(value = { "system:role:edit" })
	@RequestMapping("/save")
	public void save(@ModelAttribute Role role, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {
		try {
			/*
			// 超级管理员角色不予修改
			if (!Role.SUPER_ADMIN_ID.equals(role.getId())) {
				String[] permissionIds = request.getParameterValues("permissionIds[]");

				if (permissionIds != null) {
					role.setPermissionIds(StringUtil.join(permissionIds,","));
					//TODO
					for (String permissionId : permissionIds) {
						// 超级管理员权限不予赋予
						if (!permissionId.equals(Permission.SUPER_ID.toString())) {

						}
					}
				}
			}*/
			String[] permissionIds = request.getParameterValues("permissionIds");
			if (permissionIds != null) {
				role.setPermissionIds(StringUtils.join(permissionIds,","));
				//TODO
				/*
				for (String permissionId : permissionIds) {
					// 超级管理员权限不予赋予
					if (!permissionId.equals(Permission.SUPER_ID.toString())) {

					}
				}*/
			}
			if(StringUtils.isBlank(role.getPermissionIds())){
				role.setPermissionIds("");
			}
			if(role.getId()!=null){
				Role oldRole = roleDao.findById(role.getId());
				roleDao.update(role);
			}else{
				roleDao.insert(role);
			}
			ResponseTypeOutUtils.renderJsonSuccess(response, "角色储存成功");

		} catch (Exception e) {
			ResponseTypeOutUtils.renderJsonError(response, "角色储存失败");
			//logger.error("[{}]储存角色失败：{}", SystemUtils.getCurrentUserName(), role, e);
		}
	}

	/**
	 * 删除角色 注意请求参数名称为"ids[]"
	 * 
	 * @param ids
	 * @param request
	 * @param response
	 */
	@RequiresPermissions(value = { "system:role:delete" })
	@RequestMapping("/delete")
	public void delete(@RequestParam("ids[]") Long[] ids, HttpServletRequest request, HttpServletResponse response) {
		try {
			for (Long id : ids) {
				Role role = roleDao.findById(id);
				if(role!=null){
					roleDao.delete(role);
				}
			}
			ResponseTypeOutUtils.renderJsonSuccess(response, "删除角色成功");
		} catch (Exception e) {
			ResponseTypeOutUtils.renderJsonError(response, "删除角色失败");
			//logger.error("[{}]删除角色失败：{}", SystemUtils.getCurrentUserName(), Arrays.asList(ids), e);
		}
	}

	/**
	 * 获取角色权限
	 * 
	 * @param roleId
	 * @param request
	 * @param response
	 */
	@RequiresPermissions(value = { "system:role:read" })
	@RequestMapping("/getRolePermission")
	public void getRolePermission(HttpServletRequest request, HttpServletResponse response) {
		try {
			String roleId = request.getParameter("roleId");
			List<Permission> list = new ArrayList<Permission>();
			if (StringUtils.isNotBlank(roleId)) {
				Role role = roleDao.findById(Long.parseLong(roleId));
				list = permissionDao.getRolePermissions(role);
				role.setPermissionList(list);
			}
			String json = DataGridUtils.ListToJson(list);
			ResponseTypeOutUtils.renderJson(response, json);
		} catch (Exception e) {
			//logger.error("[{}]获取角色权限list失败", SystemUtils.getCurrentUserName(), e);
		}
	}

	/**
	 * 获取角色可选权限page(包含已经选择的)
	 * 
	 * @param roleId
	 * @param request
	 * @param response
	 */
	/*
	@RequiresPermissions(value = { "system:role:read" })
	@RequestMapping("/getChoosePermissions")
	public void getChoosePermissions(@ModelAttribute DataGridParam dataGridParam, HttpServletRequest request, HttpServletResponse response) {
		try {
			Sort sort = new Sort(Direction.valueOf(dataGridParam.getOrder()), dataGridParam.getSort());
			PageRequest pageRequest = new PageRequest(dataGridParam.getPage(), dataGridParam.getRows(), sort);
			List<Permission> page = permissionDao.getRoleChoosePermissionPage(pageRequest);
			ResponseTypeOutUtils.renderJson(response, DataGridUtils.PageToJson(page));
		} catch (Exception e) {
			logger.error("[{}]获取角色可选权限page失败：{}", SystemUtils.getCurrentUserName(), dataGridParam, e);
		}
	}*/
	
	/**
	 * 获取角色剩余可选权限page(不包含已选)
	 * 
	 * @param dataGridParam
	 * @param request
	 * @param response
	 */
	/*
	@RequiresPermissions(value = { "system:role:read" })
	@RequestMapping("/getChoosablePermission")
	public void getChoosablePermission(@ModelAttribute DataGridParam dataGridParam, HttpServletRequest request, HttpServletResponse response) {
		try {
			String roleId = request.getParameter("roleId");
			String json = "";
			if (StringUtils.isNotBlank(roleId)) {
				Role role = roleDao.getRole(Long.parseLong(roleId));
				Sort sort = new Sort(Direction.valueOf(dataGridParam.getOrder()), dataGridParam.getSort());
				PageRequest pageRequest = new PageRequest(dataGridParam.getPage(), dataGridParam.getRows(), sort);
				Page<Permission> page = permissionDao.findRoleChoosablePermission(role, pageRequest);
				json = DataGridUtils.PageToJson(page);
			}
			ResponseTypeOutUtils.renderJson(response, json);
		} catch (Exception e) {
			logger.error("[{}]获取角色可选权限page失败：{}", SystemUtils.getCurrentUserName(), dataGridParam, e);
		}
	}*/


}
